'use strict';
module.exports = {
	/**
	 * 此函数名称
	 * @url client/user/pub/login 前端调用的url参数地址
	 * data 请求参数
	 * @params {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, originalParam } = event;
		let { customUtil, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code : 0, msg : '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			code,
			type
		} = data;
		
		if (!code) {
			return { code: -1, msg: "code不能为空" };
		}
		
	

		let business = await vk.daoCenter.businessDao.findById("6780d398f019be8d7a5f5757")
		
		
		if (!business || Object.keys(business).length <= 0) {
			return { code: -1, msg: "错误数据，请联系开发者" };
		}
		
		let nickname = `${business.app_name}用户${randomCoding()}`
		let avatar = business.app_logo 
		
		
		
		// // 测试账号 ------
		const loginUtil = vk.require("service/user/util/loginUtil");
		res = await loginUtil.login({
			provider: 'wx',
			clientInfo: originalParam.context,
			openid: "oNV-n5RRlY9FoOKzskjKN-xOiy8c",
			addLog: false, // 历史原因，这里不记录日志，单独记录，因为原先日志的login_type与login的provider不一样
			appid: business.mp.appid,
			appsecret:  business.mp.appsecret
		}, util);
		console.log("res:", res)
		if (res.code !== 0) {
			// 登录失败
			return res;
		}
		return res
		
		// 标记当前平台的provider
		const provider = "wx"; // 历史原因，这里用wx，而非weixin
		
		// 如果有platform参数，则使用platform参数，否则从context中获取
		if (data.platform) originalParam.context.PLATFORM = data.platform;
		
		let platform = vk.pubfn.getPlatformForUniId(originalParam.context);
		
		// 额外写入的自定义字段数据（可以自己增加，建议只传一些显示的信息，不要传余额字段等，因为前端不可信任）
		let customData = {
			nickname,
			avatar,
			is_author: false,
			withdraw_number: 0 // 用户可提现金额
		};
		
		// 额外返回给前端的数据
		let extraRes = {};
		
		let customConfig = {};

		// 也可以打开下方注释，动态赋值appid和appsecret即可支持多小程序登录
		customConfig.appid = business.mp.appid;
		customConfig.appsecret = business.mp.appsecret;
		
		// code获取openid
		let code2SessionRes = await vk.openapi.weixin.auth.code2Session({
			context: originalParam.context, // 内部会根据context来判断是小程序还是APP还是公众号
			code,
			needKey: true, // 需要返回密钥信息
			...customConfig
		});
		if (code2SessionRes.code !== 0) {
			return code2SessionRes;
		}
		let {
			appid, // appid
			openid, // 用户的openid
			unionid, // 用户的unionid（只有绑定开放平台后才有此值）
			sessionKey, // 用户的sessionKey
			accessToken, // 用户accessToken
			refreshToken, // 用户refreshToken
			expiresIn: accessTokenExpired, // 用户accessToken过期时间
			encryptedKey, // 加密信息
		} = code2SessionRes;
		
		// 设置额外返回给前端的数据
		extraRes = {
			encryptedKey,
			openid, // 用户的openid
			unionid, // 用户的unionid
		};
		if (["h5", "h5-weixin", "app-plus"].indexOf(platform) > -1) {
			// h5 和 app 共用 app 的 getUserInfo 接口
			let getUserInfoRes = await vk.openapi.weixin.app.auth.getUserInfo({
				access_token: accessToken,
				openid: openid,
			});
			if (!customData.nickname) customData.nickname = getUserInfoRes.nickname;
			if (!customData.avatar) customData.avatar = getUserInfoRes.headimgurl;
		}
		
		
		res = await loginUtil.login({
			clientInfo: originalParam.context,
			type,
			provider,
			appid,
			openid,
			unionid,
			customData,
			extraRes,
			addLog: false, // 历史原因，这里不记录日志，单独记录，因为原先日志的login_type与login的provider不一样
		}, util);
		console.log("res:", res)
		if (res.code !== 0) {
			// 登录失败
			return res;
		}
		
		// 为了能使用官方的安全网络，微信登录成功后需要向 opendb-open-data 表插入 sessionKey
		if (vk.system.opendbOpenDataDao) {
			let platformData = {
				"mp-weixin": "weixin-mp",
				"app-plus": "weixin-app",
				"app": "weixin-app",
				"h5-weixin": "weixin-h5",
				"web-weixin": "weixin-web",
			};
			if (platformData[platform]) {
				let cacheKey = {
					appId: appid,
					platform: platformData[platform],
					openid,
				};
				await vk.system.opendbOpenDataDao.setSessionKey(cacheKey, { session_key: sessionKey }, 30 * 24 * 60 * 60);
			}
		}
		
		// 添加登录日志
		const loginLogService = vk.require("service/user/util/loginLog");
		await loginLogService.add({
			type: "login",
			login_type: "weixin",
			user_id: res.uid,
			context: originalParam.context
		}, util);
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

function randomCoding(minLength = 6, maxLength = 10) {
	const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+[]{}|;:,.<>?';
	const length = Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength;
	let result = '';
	for (let i = 0; i < length; i++) {
		const randomIndex = Math.floor(Math.random() * characters.length);
		result += characters[randomIndex];
	}
	return result;
}